import { useState, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import type { TablePagination, TableSearchField } from './types';

interface UseTableOptions<T = any> {
  queryKey: string;
  fetchData: (params: TableFetchParams) => Promise<TableFetchResponse<T>>;
  defaultPageSize?: number;
  searchFields?: TableSearchField[];
  defaultSort?: {
    field: string;
    order: 'ascend' | 'descend';
  };
  onSuccess?: (data: TableFetchResponse<T>) => void;
  onError?: (error: any) => void;
}

interface TableFetchParams {
  page: number;
  pageSize: number;
  search?: Record<string, any>;
  sort?: {
    field: string;
    order: 'ascend' | 'descend';
  };
}

interface TableFetchResponse<T> {
  data: T[];
  total: number;
  page: number;
  pageSize: number;
}

export const useTableSimple = <T extends Record<string, any>>(options: UseTableOptions<T>) => {
  const {
    queryKey,
    fetchData,
    defaultPageSize = 10,
    searchFields = [],
    defaultSort,
    onSuccess,
    onError,
  } = options;

  // 简单的状态管理
  const [state, setState] = useState({
    currentPage: 1,
    pageSize: defaultPageSize,
    total: 0,
    searchParams: {} as Record<string, any>,
    sortParams: defaultSort,
  });

  // 更新分页状态
  const setPagination = useCallback((page: number, pageSize: number) => {
    console.log('2. 分页状态更新:', { page, pageSize });
    setState(prev => ({
      ...prev,
      currentPage: page,
      pageSize,
    }));
  }, []);

  // 更新搜索参数
  const setSearch = useCallback((params: Record<string, any>) => {
    setState(prev => ({
      ...prev,
      searchParams: params,
      currentPage: 1, // 重置到第一页
    }));
  }, []);

  // 更新排序参数
  const setSort = useCallback((sort: { field: string; order: 'ascend' | 'descend' } | undefined) => {
    setState(prev => ({
      ...prev,
      sortParams: sort,
    }));
  }, []);

  // 直接使用state作为queryKey的依赖
  const queryKeyString = JSON.stringify({
    queryKey,
    currentPage: state.currentPage,
    pageSize: state.pageSize,
    searchParams: state.searchParams,
    sortParams: state.sortParams,
  });

  // 获取数据
  const {
    data: tableData,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: [queryKeyString],
    queryFn: async () => {
      console.log('5. 开始获取数据:', {
        page: state.currentPage,
        pageSize: state.pageSize,
        search: state.searchParams,
        sort: state.sortParams
      });

      const params: TableFetchParams = {
        page: state.currentPage,
        pageSize: state.pageSize,
        search: Object.keys(state.searchParams).length > 0 ? state.searchParams : undefined,
        sort: state.sortParams,
      };

      try {
        const response = await fetchData(params);
        console.log('5. 获取数据完成:', {
          page: state.currentPage,
          pageSize: state.pageSize,
          total: response.total,
          dataLength: response.data?.length || 0
        });

        // 更新总数
        setState(prev => ({
          ...prev,
          total: response.total,
        }));

        onSuccess?.(response);
        return response;
      } catch (error) {
        onError?.(error);
        throw error;
      }
    },
    enabled: true,
  });

  // 分页配置
  const pagination: TablePagination = {
    current: state.currentPage,
    pageSize: state.pageSize,
    total: state.total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100'],
  };

  // 处理搜索
  const handleSearch = useCallback((params: Record<string, any>) => {
    setSearch(params);
  }, [setSearch]);

  // 处理表格变化
  const handleTableChange = useCallback((newPagination: TablePagination, filters: Record<string, any>, sorter: any) => {
    console.log('1. Table 组件触发分页 onChange 事件:', {
      current: newPagination.current,
      pageSize: newPagination.pageSize
    });

    // 处理分页变化
    if (newPagination.current !== state.currentPage || newPagination.pageSize !== state.pageSize) {
      setPagination(newPagination.current, newPagination.pageSize);
    }

    // 处理排序变化
    if (sorter.field && sorter.order) {
      setSort({
        field: sorter.field,
        order: sorter.order,
      });
    } else {
      setSort(undefined);
    }
  }, [state.currentPage, state.pageSize, setPagination, setSort]);

  // 刷新数据
  const refresh = useCallback(() => {
    refetch();
  }, [refetch]);

  return {
    data: tableData?.data || [],
    total: tableData?.total || 0,
    loading: isLoading,
    error,
    pagination,
    searchParams: state.searchParams,
    searchFields,
    handleSearch,
    handleTableChange,
    refresh,
  };
};